2.webview_flutter 加载监听
网页加载监听 NavigationDelegate
NavigationDelegate 中包含一系列回调:
- onNavigationRequest:是否拦截请求
- onPageStarted:页面跳转开始
- onPageFinished:页面跳转结束
- onProgress:网页加载进度
- onWebResourceError:网络资源错误
- onUrlChange:url 发生变化
- onHttpAuthRequest 网页权限请求
- onHttpError:请求错误
监听网页加载进度
controller
..setNavigationDelegate(
NavigationDelegate(
onProgress: (int progress) {
debugPrint('WebView is loading (progress : $progress%)');
},
onPageStarted: (String url) {
debugPrint('Page started loading: $url');
},
onPageFinished: (String url) {
debugPrint('Page finished loading: $url');
},
onUrlChange: (UrlChange change) {
debugPrint('url change to ${change.url}');
},
监听资源加载错误
controller
..setNavigationDelegate(
NavigationDelegate(
onWebResourceError: (WebResourceError error) {
debugPrint('''
Page resource error:
code: ${error.errorCode}
description: ${error.description}
errorType: ${error.errorType}
isForMainFrame: ${error.isForMainFrame}
''');
},
onHttpError: (HttpResponseError error) {
debugPrint('Error occurred on page: ${error.response?.statusCode}');
},
),
)
网页请求拦截
controller
..setNavigationDelegate(
NavigationDelegate(
onNavigationRequest: (NavigationRequest request) {
if (!request.url.startsWith('http')) {
debugPrint('blocking navigation to ${request.url}');
return NavigationDecision.prevent;
}
if (request.url.startsWith('https://www.youtube.com/')) {
debugPrint('blocking navigation to ${request.url}');
return NavigationDecision.prevent;
}
debugPrint('allowing navigation to ${request.url}');
return NavigationDecision.navigate;
},
),
)
本文作者:Maeiee
版权声明:如无特别声明,本文即为原创文章,版权归 Maeiee 所有,未经允许不得转载!
喜欢我文章的朋友请随缘打赏,鼓励我创作更多更好的作品!